#!/usr/bin/python
# -*- coding: utf-8 -*-

import gtk
import threading, thread
import urllib, urllib2, time, datetime, os, gobject
import HTMLParser
h = HTMLParser.HTMLParser()
import gettext, locale

def setTextDomain():
	GETTEXT_DOMAIN = 'YouTube'
	LOCALE_PATH = os.path.join(os.path.dirname(os.path.abspath( __file__ )), 'i18n')
	locale.setlocale(locale.LC_ALL, '')
	for module in gtk.glade, gettext:
		module.bindtextdomain(GETTEXT_DOMAIN, LOCALE_PATH)
		module.textdomain(GETTEXT_DOMAIN)

class Main:
	def __init__(self):
		setTextDomain()
		self.pluginName = 'YouTube'
		self.author = 'Ovidiu D. Niţan'
		self.version = '0.27'
		self.descriere = _('Plugin for downloading videos from YouTube')
		self.updatecheck = 'http://redoxwap.freehostia.com/pymaxe_update.php?action=plugin_version&plugin=YouTube'

	def start(self, pymaxe):
		try:
			pymaxe.youtubeMenu
		except:
			pymaxe.youtubeMenu = gtk.RadioMenuItem(pymaxe.gui.get_object('radiomenuitem1'), 'YouTube')
			pymaxe.youtubeMenu.show()
			pymaxe.gui.get_object('menu2').prepend(pymaxe.youtubeMenu)
			pymaxe.sites[self.pluginName] = 'youtube.com'
	
	def search(self, pymaxe, string):
		video = gtk.gdk.pixbuf_new_from_file(__path__[0] + '/youtube.png')
		print "[plugin] YouTube: searching for " +  string
		if pymaxe.getSetting('Plugins', 'YTresults') == None:
			results = '10'
		else:
			results = pymaxe.getSetting('Plugins', 'YTresults')
		req = urllib2.Request('http://gdata.youtube.com/feeds/api/videos?q=' + urllib.quote(string) + '&max-results='+results);
		getdata = urllib2.urlopen(req);
		data = getdata.read();
		results = data.split('<entry>')
		results.pop(0)
		for x in results:
			try:
				gid = x.split('<id>')
				gid = gid[1].split('</id>')
				url = gid[0]
				gdesc = x.split('<media:description type=\'plain\'>')
				gdesc = gdesc[1].split('</media:description>')
				desc = gdesc[0]
				desc = h.unescape(desc)
				gtitle = x.split("<title type='text'>");
				gtitle = gtitle[1].split('</title>')
				title = urllib.unquote(gtitle[0])
				title = '<b>' + title + '</b>\n<i>' + desc.replace('\n', '').replace('&', '&amp;') + '</i>'
				gtime = x.split("duration='");
				gtime = gtime[1].split("'");
				timp = str(datetime.timedelta(seconds=int(gtime[0])))[2:]
				gobject.idle_add(pymaxe.addToList, [video, title, timp, url])
			except Exception, e:
				#print str(e)
				pass

	def getDetails(self, pymaxe, url):
		setTextDomain()
		pymaxe.doConvert = 'audio'
		gtkb = gtk.Builder()
		gtkb.add_from_file(__path__[0] + '/ytgui.glade')
		qSelect = gtkb.get_object('vbox1')
		gtkb.get_object('lowquality').set_active(True)
		gtkb.get_object('hiquality').set_sensitive(False)
		gtkb.get_object('hdquality').set_sensitive(False)
		gtkb.get_object('hdquality1').set_sensitive(False)
		gtkb.get_object('lowquality').props.name = 'lowquality'
		gtkb.get_object('hiquality').props.name = 'hiquality'
		gtkb.get_object('hdquality').props.name = 'hdquality'
		gtkb.get_object('hdquality1').props.name = 'hdquality1'
		data = self.fileData(url)
		if data == False:
			pymaxe.isWorking = False
			gobject.idle_add(self.showDialog, gtk.MESSAGE_ERROR, 'YouTube: Error', 'Cannot parse data. Please try later or contact plugin\'s author.')
			gobject.idle_add(pymaxe.restoreState)
			return False
		calitati = data['calitati']
		if calitati.has_key('37'):
			gtkb.get_object('hdquality').set_sensitive(True)
		if calitati.has_key('22'):
			gtkb.get_object('hdquality1').set_sensitive(True)
		if calitati.has_key('18'):
			gtkb.get_object('hiquality').set_sensitive(True)
		#gobject.idle_add(pymaxe.showDetails, url, titlu, timp, 'video', qSelect, 'YouTube')
		gobject.idle_add(pymaxe.showDetails, data, qSelect, self.getDownloadURL)
		gtkb.get_object('checkbutton5').set_active(self.str2bool(pymaxe.getSetting('General', 'noconvert')))
		gtkb.connect_signals({"changeQuality" : (self.changeQuality, data),
				      "changeType" : (self.changeType, pymaxe, gtkb)})
		threading.Thread(target=self.YTpreview, args=(data['vcode'], gtkb.get_object('image1'), pymaxe)).start()

	def fileData(self, url):
		vcode = os.path.basename(url)
		try:
			gvcode = vcode.split('v=')
			gvcode = gvcode[1].split('&')
			vcode = gvcode[0]
		except:
			vcode = vcode
		url = 'http://www.youtube.com/watch?v=' + vcode
		try:
			req = urllib2.Request(url);
			getdata = urllib2.urlopen(req);
			data = getdata.read();
			gtitlu = data.split('name="title" content="')
			gtitlu = gtitlu[1].split('">')
			titlu = gtitlu[0]
			gtimp = data.split('&length_seconds=')
			gtimp = gtimp[1].split('&')
			timp = str(datetime.timedelta(seconds=int(gtimp[0])))[2:]
			gt = data.split('&t=')
			gt = gt[1].split('&')
			t = urllib.unquote(gt[0])
			gq = data.split('&fmt_url_map=')
			gq = gq[1].split('&')
			qualities = urllib.unquote(gq[0])
			qualities = qualities.split(',')
			calitati = {}
			for x in qualities:
				y = x.split('|')
				i = y[0]
				urlCalitate = y[1]
				calitati[i] = urlCalitate
			downurl = calitati['34']
			data = {"url" : url,
				"titlu" : titlu,
				"durata" : timp,
				"extensie" : '.mp3',
				"tip" : '.mp3',
				"downurl" : downurl,
				"format" : 'Video',
				'calitati' : calitati,
				'vcode' : vcode}
			self.downURL = data['downurl']
			return data
		except Exception, e:
			print e
			return False
	

	def changeType(self, obj, pymaxe, gui):
		currentName = pymaxe.gui.get_object('entry2').get_text()
		currentName = os.path.splitext(currentName)[0]
		if gui.get_object('radiobutton1').get_active():
			gui.get_object('checkbutton5').set_sensitive(False)
			pymaxe.gui.get_object('entry2').set_text(currentName + '.mp3')
			pymaxe.doConvert = 'audio'
		if gui.get_object('radiobutton2').get_active():
			gui.get_object('checkbutton5').set_sensitive(True)
			pymaxe.gui.get_object('entry2').set_text(currentName + '.avi')
			if gui.get_object('checkbutton5').get_active():
				pymaxe.doConvert = False
				pymaxe.gui.get_object('entry2').set_text(currentName + '.mp4')
			else:
				pymaxe.doConvert = 'video'
				pymaxe.gui.get_object('entry2').set_text(currentName + '.avi')
		
	def showDialog(self, type, title, message):
			gtk.gdk.threads_enter()
			dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=message);
			dialog.set_title(title);
			dialog.run();
			dialog.destroy();
			gtk.gdk.threads_leave()
	
	def changeQuality(self, obj, data):
		if obj.props.name == 'lowquality':
			 self.downURL = data['downurl']
		elif obj.props.name == 'hiquality':
			 self.downURL = data['downurl'] + '&fmt=18'
		elif obj.props.name == 'hdquality':
			 self.downURL = data['downurl'] + '&fmt=37'
		elif obj.props.name == 'hdquality1':
			 self.downURL = data['downurl'] + '&fmt=22'
			 
	def getDownloadURL(self):
		return self.downURL
			 
	def config(self, pymaxe):
		setTextDomain()
		gui = gtk.Builder()
		gui.add_from_file(__path__[0] + '/ytconfig.glade')
		gui.connect_signals({"changeValue" : (self.changeValue, pymaxe), "close" : (self.close, gui)})
		if pymaxe.getSetting('Plugins', 'YTresults') == None:
			gui.get_object('spinbutton1').set_value(10)
		else:
			gui.get_object('spinbutton1').set_value(int(pymaxe.getSetting('Plugins', 'YTresults')))
	
	def changeValue(self, obj, pymaxe):
		res = int(obj.get_value())
		pymaxe.setSetting('Plugins', 'YTresults', str(res))

	def str2bool(self, v):
		return v.lower() in ["yes", "true", "t", "1"]

	def YTpreview(self, vcode, img, pymaxe):
		urls = []
		urls.append('http://i4.ytimg.com/vi/' + vcode + '/1.jpg')
		urls.append('http://i4.ytimg.com/vi/' + vcode + '/2.jpg')
		urls.append('http://i4.ytimg.com/vi/' + vcode + '/3.jpg')
		while not pymaxe.gui.get_object('details').get_property('visible'):
			time.sleep(0.2)
		while True:
			for url in urls:
				if not pymaxe.gui.get_object('vbox3').get_property('sensitive'):
					return False
				if not pymaxe.gui.get_object('details').get_property('visible'):
					return 
				req = urllib2.Request(url);
				getdata = urllib2.urlopen(req);
				data = getdata.read();
				pbl = gtk.gdk.PixbufLoader()
				pbl.write(data)
				pbl.close()
				gobject.idle_add(img.set_from_pixbuf, pbl.get_pixbuf())
				time.sleep(3)
	
	def close(self, obj, gui):
		gui.get_object('window1').destroy()

	def quit(self):
		exit()
			 
	def uninstall(self, pymaxe):
		pymaxe.youtubeMenu.destroy()
		del pymaxe.youtubeMenu
